<template>
  <div class="map-container">
    <!-- 搜索栏区域 -->
    <el-card class="search-bar">
      <el-row :gutter="20">
        <el-col :span="4">
          <div class="info-item">
            <span>总条数：</span>
            <el-tag>{{ totalElements }}</el-tag>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="info-item">
            <span>总页数：</span>
            <el-tag>{{ totalPages }}</el-tag>
          </div>
        </el-col>
        <el-col :span="4">
          <el-input v-model="searchForm.targetId" placeholder="targetId" clearable/>
        </el-col>
        <el-col :span="4">
          <el-select 
            v-model="searchForm.routeId" 
            placeholder="选择路径" 
            clearable
            filterable
            @change="handleSearch"
          >
            <el-option 
              v-for="route in routeOptions" 
              :key="route.routeId" 
              :label="route.routeId + (route.startPoint && route.endPoint ? ` (${route.startPoint} -> ${route.endPoint})` : '')"
              :value="route.routeId"
            />
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-input-number 
            v-model="searchForm.page" 
            placeholder="page" 
            :min="0"
            controls-position="right"
            style="width: 120px"
          />
        </el-col>
        <el-col :span="3">
          <el-input-number 
            v-model="searchForm.size" 
            placeholder="size" 
            :min="1"
            controls-position="right"
            style="width: 120px"
          />
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="handleSearch" style="width: 100%">
            刷新
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 地图容器 -->
    <div id="tencent-map-container" class="map"/>
  </div>
</template>

<script>
import api from "../api/api"
//导入坐标转换工具
import transformation from "../utils/transformation";
//获取消息提示对象，用于显示错误消息
import {useMessage} from "naive-ui"
/* createTMapLatLng：将 WGS84 坐标转换为 GCJ-02（火星坐标系）后，返回腾讯地图支持的 LatLng 对象。 */
function createTMapLatLng(lat, lng) {
  let lngLat = transformation.wgs84ToGcj02(lng, lat)
  lng = lngLat[0]
  lat = lngLat[1]
  return new window.TMap.LatLng(lat, lng)
}
/* createTMapLatLngList：批量处理位置列表，将每个坐标转换为 GCJ-02 坐标。 */
function createTMapLatLngList(locations) {
  let tMapLatLngList = []
  locations.forEach(location => {
    tMapLatLngList.push(createTMapLatLng(location.lat, location.lng))
  })
  return tMapLatLngList
}
/* initMap：初始化地图对象，设置中心点、缩放级别、俯仰角和旋转角度。 */
function initMap(lat, lng) {
  //定义map变量，调用 TMap.Map() 构造函数创建地图
  return new window.TMap.Map(document.getElementById('tencent-map-container'), {
    center: new createTMapLatLng(lat, lng), //设置地图中心点坐标
    zoom: 15, //设置地图缩放级别
    pitch: 0, //设置俯仰角
    rotation: 0 //设置地图旋转角度
  });
}
/* initMultiPolyline：创建一个折线图层，将路径显示在地图上。 */
function initMultiPolyline(map, paths) {
  return new window.TMap.MultiPolyline({
    id: 'default-polyline-layer', //图层唯一标识
    map: map,//设置折线图层显示到哪个地实例中
    //折线样式定义
    styles: {
      'style_blue': new window.TMap.PolylineStyle({
        'color': '#ff3737', //线填充色
        'width': 2, //折线宽度
        'borderWidth': 0, //边线宽度
        'borderColor': '#FFFFFF', //边线颜色
        'lineCap': 'round' //线端头方式
      }),
    },
    geometries: [
      {
        'id': "default-multi-polyline",
        'styleId': 'style_blue',
        'paths': paths
      }
    ]
  });
}

let map = null
let multiPolyline = null

export default {
  name: "tencent-map",
  setup() {
    const message = useMessage()
    return {
      message
    }
  },
  data() {
    return {
      totalElements: null,
      totalPages: null,
      searchForm: {
        targetId: null,
        routeId: null,
        size: 3000,//设置显示的坐标点数量
        page: 0
      },
      lat: null,
      lng: null,
      routeOptions: [], // 添加路径选项数组
    }
  },
  methods: {
    handleSearch() {
      this.handleClick()
    },
    handleClick() {
      setTimeout(() => {
        api.getLocations(
          this.searchForm.targetId, 
          this.searchForm.routeId, 
          this.searchForm.page, 
          this.searchForm.size
        ).then(async response => {
          console.log(response)
          this.totalElements = response.totalElements
          this.totalPages = response.totalPages

          // 无论是否有足够的点，都先清除旧地图
          if (map) {
            map.destroy()  // 销毁旧地图
          }

          let locations = response.content
          if (locations.length > 1) {
            // 重新初始化地图和路径线
            map = initMap(locations[0].lat, locations[0].lng)
            multiPolyline = initMultiPolyline(map, createTMapLatLngList(locations))
            
            // 获取路径详情
            const routeInfo = await this.getRouteInfo(this.searchForm.routeId)

            // 添加起点标记
            const startMarker = new window.TMap.MultiLabel({
              map: map,
              styles: {
                'label': new window.TMap.LabelStyle({
                  color: '#67C23A',
                  fontSize: '20px',
                  fontWeight: 'bold',
                  backgroundColor: '#fff',
                  padding: '8px 12px',
                  borderRadius: '4px',
                  borderWidth: 2,
                  borderColor: '#67C23A',
                  offset: { x: 0, y: 0 }
                })
              },
              geometries: [{
                id: 'start-label',
                styleId: 'label',
                position: createTMapLatLng(locations[0].lat, locations[0].lng),
                content: '起'
              }]
            })

            // 添加终点标记
            const endMarker = new window.TMap.MultiLabel({
              map: map,
              styles: {
                'label': new window.TMap.LabelStyle({
                  color: '#F56C6C',
                  fontSize: '20px',
                  fontWeight: 'bold',
                  backgroundColor: '#fff',
                  padding: '8px 12px',
                  borderRadius: '4px',
                  borderWidth: 2,
                  borderColor: '#F56C6C',
                  offset: { x: 0, y: 0 }
                })
              },
              geometries: [{
                id: 'end-label',
                styleId: 'label',
                position: createTMapLatLng(locations[locations.length - 1].lat, locations[locations.length - 1].lng),
                content: '终'
              }]
            })

            // 添加点击事件监听
            startMarker.on('click', () => this.handleStartClick())
            endMarker.on('click', () => this.handleEndClick())
          } else {
            // 如果点数不足，初始化一个空地图
            map = new window.TMap.Map(document.getElementById('tencent-map-container'), {
              center: new window.TMap.LatLng(39.908802, 116.397502),  // 默认北京中心
              zoom: 12
            })
            this.message.warning("位置点数量不足，无法绘制路径")
          }
        })
      }, 100)
    },
    async getRouteInfo(routeId) {
      if (!routeId) {
        this.message.warning('请先选择路径')
        return null
      }
      try {
        const response = await api.getRouteDetail(routeId)
        return response.data
      } catch (error) {
        this.message.error('获取路径详情失败')
        return null
      }
    },
    async handleStartClick() {
      const routeInfo = await this.getRouteInfo(this.searchForm.routeId)
      if (routeInfo) {
        this.message.info(`起点：${routeInfo.startPoint || '未设置起点名称'}`)
      }
    },
    async handleEndClick() {
      const routeInfo = await this.getRouteInfo(this.searchForm.routeId)
      if (routeInfo) {
        this.message.info(`终点：${routeInfo.endPoint || '未设置终点名称'}`)
      }
    },
    // 获取路径列表
    async fetchRouteOptions() {
      try {
        const response = await api.getRoutes('/routes')
        this.routeOptions = response.data || []
      } catch (error) {
        this.message.error('获取路径列表失败')
      }
    },
  },
  beforeMount() {
    setTimeout(() => {
      api.getLocations(
        this.searchForm.targetId, 
        this.searchForm.routeId, 
        this.searchForm.page, 
        this.searchForm.size
      ).then(async response => {
        this.totalElements = response.totalElements
        this.totalPages = response.totalPages

        let locations = response.content
        if (locations.length > 1) {
          // 获取路径详情
          const routeInfo = await this.getRouteInfo(this.searchForm.routeId)
          
          map = initMap(locations[0].lat, locations[0].lng)
          multiPolyline = initMultiPolyline(map, createTMapLatLngList(locations))

          // 添加起点标记
          const startMarker = new window.TMap.MultiLabel({
            map: map,
            styles: {
              'label': new window.TMap.LabelStyle({
                color: '#67C23A',
                fontSize: '20px',
                fontWeight: 'bold',
                backgroundColor: '#fff',
                padding: '8px 12px',
                borderRadius: '4px',
                borderWidth: 2,
                borderColor: '#67C23A',
                offset: { x: 0, y: 0 }
              })
            },
            geometries: [{
              id: 'start-label',
              styleId: 'label',
              position: createTMapLatLng(locations[0].lat, locations[0].lng),
              content: '起'
            }]
          })

          // 添加终点标记
          const endMarker = new window.TMap.MultiLabel({
            map: map,
            styles: {
              'label': new window.TMap.LabelStyle({
                color: '#F56C6C',
                fontSize: '20px',
                fontWeight: 'bold',
                backgroundColor: '#fff',
                padding: '8px 12px',
                borderRadius: '4px',
                borderWidth: 2,
                borderColor: '#F56C6C',
                offset: { x: 0, y: 0 }
              })
            },
            geometries: [{
              id: 'end-label',
              styleId: 'label',
              position: createTMapLatLng(locations[locations.length - 1].lat, locations[locations.length - 1].lng),
              content: '终'
            }]
          })

          // 添加点击事件监听
          startMarker.on('click', () => this.handleStartClick())
          endMarker.on('click', () => this.handleEndClick())
        } else {
          this.message.error("locations < 2, 不能绘制折线")
        }
      })
    }, 100)  // 添加 100ms 延时
  },
  async created() {
    // 在组件创建时获取路径列表
    await this.fetchRouteOptions()
  }
}


</script>
<style scoped>
.map-container {
  position: relative;
  width: 100%;
  height: 100vh;
  padding: 10px;
  box-sizing: border-box;
}

.search-bar {
  position: absolute;
  top: 10px;
  left: 10px;
  right: 10px;
  z-index: 9999;
  background-color: rgba(255, 255, 255, 0.95);
  pointer-events: auto;
}

.map {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-input-number) {
  width: 120px !important;
}

:deep(.el-input-number .el-input__inner) {
  padding-right: 30px !important;
  text-align: center;
}

:deep(.el-input) {
  width: 100%;
}

:deep(.el-button) {
  width: 100%;
}

:deep(.el-card) {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.el-select) {
  width: 100%;
}
</style>
